package com.atnjupt.json.jsontest;

import com.atnjupt.json.bean.Student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Wizarder
 * @create 2021-06-28 11:38
 */
public class JsonTest {
    @Test
    public void test(){
        //javabean和json互相转换
        Student student = new Student(1,"luhu");
        Gson gson = new Gson();
        String studentToJsonSting = gson.toJson(student);
        System.out.println(studentToJsonSting);
        Student jsonStringToStudent = gson.fromJson(studentToJsonSting, Student.class);
        System.out.println(jsonStringToStudent);

    }
    @Test
    public void test2(){
        //list集合和json相互转换
        List<Student> studentList = new ArrayList<>();
        Gson gson = new Gson();
        studentList.add(new Student(1,"luhu"));
        studentList.add(new Student(2,"wizarder"));
        String studentListToString = gson.toJson(studentList);
        System.out.println(studentListToString);
        List<Student> list = gson.fromJson(studentListToString, new StudentType().getType());
        System.out.println(list);
        Student student = list.get(0);
        System.out.println(student);
    }
    @Test
    public void test3(){
        //map集合和json的互相转换
        Map<Integer,Student> studentMap = new HashMap<>();
        studentMap.put(1,new Student(1,"luhu"));
        studentMap.put(2,new Student(2,"wuyanzu"));
        Gson gson = new Gson();
        String studentMapString = gson.toJson(studentMap);
        System.out.println(studentMapString);
        //每次转换都需要创建一个类继承TypeToken这个类，会导致很多这样的类型产生。因此用匿名类来实现
//        Map<Integer,Student> mapStudent = gson.fromJson(studentMapString, new StudentMap().getType());
        Map<Integer,String > mapStudent = gson.fromJson(studentMapString,new TypeToken<Map<Integer,Student>>(){}.getType());
        System.out.println(mapStudent);
    }
}
